package org.visionlibrary.image.filters.bluring;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class BasicBlurHorizontal extends AbstractFilter {
	protected int radius = 3;

	public BasicBlurHorizontal() {
		this(3);
	}

	public BasicBlurHorizontal(int horizontalradius) {
		this.radius = horizontalradius;
	}

	public int getRadius() {
		return radius;
	}

	public void setRadius(int radius) {
		this.radius = radius;
	}

	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		int maxX = src.getWidth();
		int maxY = src.getHeight();

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					int total = 0;
					for (int kx = -radius; kx <= radius; ++kx) {
						int nx = x;

						if (nx + kx < 0)
							nx = -kx;
						else if (nx + kx >= maxX)
							nx = maxX - 1 - kx;

						total += src.getSample(nx + kx, y, ch);
					}

					int newPixelVal = total / (radius * 2 + 1);
					dest.setSample(x, y, ch, newPixelVal);
				}
			}

		return dest;
	}
}
